package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 服务人员/机构银行账号 服务实现类
 * </p>
 * @author JIAN
 * @since 2024-08-29
 */
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {
    @Resource
    IServeProviderService serveProviderService;

    @Override
    @Transactional
    public void upsertBankAccount(BankAccountUpsertReqDTO bankAccountUpsertReqDTO) {
        Long userId = UserContext.currentUserId();
        ServeProvider serveProvider = serveProviderService.getById(userId);
        if (ObjectUtils.isEmpty(serveProvider)) {
            throw new ForbiddenOperationException("当前用户不存在");
        }

        BankAccount bankAccount = BeanUtils.toBean(bankAccountUpsertReqDTO, BankAccount.class);
        bankAccount.setId(userId);
        bankAccount.setType(serveProvider.getType());

        if (ObjectUtils.isEmpty(baseMapper.selectById(userId))) {
            baseMapper.insert(bankAccount);
        } else {
            baseMapper.updateById(bankAccount);
        }
    }

    @Override
    public BankAccountResDTO getCurrentUserBankAccount() {
        Long userId = UserContext.currentUserId();
        if (ObjectUtils.isEmpty(userId)) {
            throw new ForbiddenOperationException("当前用户不存在");
        }

        BankAccount bankAccount = baseMapper.selectById(userId);
        return ObjectUtils.isEmpty(bankAccount)
                ? new BankAccountResDTO()
                : BeanUtils.toBean(bankAccount, BankAccountResDTO.class);
    }
}